//
//  LJCustomTextView.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/7/30.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "LJCustomTextView.h"

@interface LJCustomTextView ()<UITextViewDelegate>

//默认提示lab
@property (nonatomic, strong) UILabel *placeholderLab;

@end

@implementation LJCustomTextView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.textLength = 255;
        self.delegate = self;
        self.placeholderLab = [UILabel new];
        self.placeholderLab.textColor = HexColor(0xDBDCE6);
        self.placeholderLab.font = [UIFont systemFontOfSize:14];
        [self addSubview:self.placeholderLab];
    }
    return self;
}

-(void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    self.placeholderLab.text = placeholder;
    [self.placeholderLab sizeToFit];
    self.placeholderLab.nim_left = 6;
    self.placeholderLab.nim_top = 8;
}

-(void)setTextLength:(NSInteger)textLength {
    _textLength = textLength;
}

-(void)setCustomText:(NSString *)customText {
    _customText = customText;
    self.text = customText;
    [self.delegate textViewDidChange:self];
}

-(void)textViewDidChange:(UITextView *)textView {
    if (self.text.length == 0) {
        _placeholderLab.hidden = NO;
    }else{
        _placeholderLab.hidden = YES;
    }
    NSString *toBeString = self.text;
    NSString *primaryLanguageStr = self.textInputMode.primaryLanguage; // 键盘输入模式
    if ([primaryLanguageStr isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [self markedTextRange];
        //获取高亮部分
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > _textLength) {
//                if (_interception) {
                    self.text = [toBeString substringToIndex:_textLength];
//                }else {
//
//                }
                [self changeCountLab];
            }else {
                [self changeCountLab];
            }
        }else {
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else {
        //中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > _textLength) {
//            if (_interception) {
                self.text = [toBeString substringToIndex:_textLength];
//            }else {
                [self changeCountLab];
//            }
        }else {
            [self changeCountLab];
        }
    }
    
}

- (void)changeCountLab {
    NSString *changeStr = [NSString stringWithFormat:@"%ld/%ld",self.text.length,_textLength];
    if (self.countBlock) {
        self.countBlock(changeStr);
    }
}

@end
